const MYSQL = require("../../sql/mysql");
const MYSQLConfig = require("../../sql/database");
const listSQLName = "goods_list";
const specsSqlName = "goods_specs";

const { formatTypeList, goodsDataHandle } = require("./format");

// 商城服务表
const shoppingServiceSqlName = "shopping_service";
// 商城规格Key
const shoppingSpecsKeySqlName = "shopping_specs_key";
// 商品规格标签表
const specsTagSqlName = "goods_specs_tag";
// 商城规格标签表
const shoppingTagSqlName = "shopping_specs_tag";
// 商品服务表
const goodsServiceSqlName = "goods_service";
// 商品SKU表
const goodsSkuSqlName = "goods_sku";
// 商品SPU表
const goodsSpuSqlName = "goods_spu";
// 用户购物车表
const userGoodsCartSqlName = "shopping_user_cart";
// 用户收藏表
const userGoodsCollectSqlName = "";
// 用户商品浏览记录
const userGoodsBrowseSqlName = "shopping_user_goods_browse";
// 商城店铺表
const shoppingStoreSqlName = "shopping_store";
// 商城类目表
const shoppingTypeSqlName = "shopping_type";

// 运费模板列表
const shoppingCarryTemplateList = async (params = {}) => {};
// 新增运费模板
const addShoppingCarryTemplateList = async (params = {}) => {};
// 删除运费模版
const removeShoppingCarryTemplateList = async (params = {}) => {};
// 编辑运费模版
const updateShoppingCarryTemplateList = async (params = {}) => {};

// 我的收藏列表
const collectList = async (params = {}) => {
  try {
    let { user } = params;
    if (!user) {
    }
    try {
      let query = `SELECT * FROM ${userGoodsCollectSqlName}
        where user = ${user}
      `;
      let result = await MYSQL.promise().query(query);
      return {
        code: 0,
        msg: "获取成功",
        data: {
          list: result[0],
        },
      };
    } catch (error) {
      console.log(error);
      throw {
        code: 500,
        msg: "获取收藏失败,数据库操作出错",
      };
    }
  } catch (error) {
    throw error;
  }
};
// 添加收藏
const addCollect = async (params = {}) => {
  try {
    let { user, goods } = params;
    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    } else if (!goods) {
      throw {
        code: 500,
        msg: "goods不能为空",
      };
    }
    try {
      await MYSQL.promise().query(
        `INSERT INTO ${userGoodsCollectSqlName} SET ?`,
        {
          user,
          goods,
          state: 1,
        }
      );
      return {
        code: 0,
        msg: "收藏成功",
      };
    } catch (error) {
      throw {
        code: 500,
        msg: "新增失败，数据库操作错误",
      };
    }
  } catch (error) {
    throw error;
  }
};
// 取消收藏
const cancelCollect = async (params = {}) => {};

// 购物车列表  (完成)
const goodsCartList = async (params = {}) => {
  try {
    let { user } = params;

    if (!user) {
      throw { code: 500, msg: "用户不能为空" };
    }

    let query = `
      SELECT 
      user_cart.id,
      user_cart.goods_id,
      ${goodsSkuSqlName}.name,
      ${goodsSkuSqlName}.img,
      user_cart.number, -- 数量
      ${goodsSkuSqlName}.sku_id, -- skuid
      ${goodsSkuSqlName}.price, -- 单价
      (user_cart.number * ${goodsSkuSqlName}.price) as total_price,  -- 总价
      user_cart.state
      FROM ${userGoodsCartSqlName} as user_cart 
      LEFT JOIN ${goodsSkuSqlName}
      ON user_cart.sku_id = ${goodsSkuSqlName}.id
      WHERE user_cart.user = ${user}
    `;

    console.log(query);

    let result = await MYSQL.promise().query(query);

    return {
      code: 0,
      msg: "获取成功",
      data: result[0],
    };
  } catch (error) {
    console.log(error);
    throw {
      code: 500,
      msg: "获取购物车失败",
    };
  }
};
// 删除购物车商品  (完成)
const removeGoodsCart = async (params = {}) => {
  try {
    let { user, goods } = params;
    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    } else if (!goods) {
      throw {
        code: 500,
        msg: "goods不能为空",
      };
    }
    try {
      await MYSQL.promise().query(
        `DELETE FROM ${userGoodsCartSqlName} 
      WHERE
      user = '${user}'
      and
      goods = ${goods}
      `
      );
    } catch (error) {
      console.log(error);
      throw { code: 500, msg: "删除购物车商品失败,数据库操作出错" };
    }

    return {
      code: 0,
      msg: "删除成功",
    };
  } catch (error) {
    throw error;
  }
};
// 加入购物车  (完成)
const addGoodsCart = async (params = {}) => {
  try {
    let { user, goods } = params;
    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    } else if (!goods) {
      throw {
        code: 500,
        msg: "goods不能为空",
      };
    }
    try {
      await MYSQL.promise().query(`INSERT INTO ${userGoodsCartSqlName} SET ?`, {
        user,
        goods,
        state: 1,
      });
    } catch (error) {
      console.log(error);
      throw { code: 500, msg: "加入购物车失败,数据库操作出错" };
    }
    return {
      code: 0,
      msg: "加入成功",
    };
  } catch (error) {
    throw error;
  }
};

// 新增商品浏览记录 (完成)
const addGoodsBrowse = async (params = {}) => {
  try {
    let { user, goods } = params;
    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    } else if (!goods) {
      throw {
        code: 500,
        msg: "goods不能为空",
      };
    }
    try {
      await MYSQL.promise().query(
        `INSERT INTO ${userGoodsBrowseSqlName} SET ?`,
        {
          user,
          goods,
          state: 1,
        }
      );
    } catch (error) {
      throw {
        code: 500,
        msg: "新增失败，数据库操作错误",
      };
    }

    return {
      code: 0,
      msg: "新增成功",
    };
  } catch (error) {
    throw error;
  }
};
// 删除商品浏览记录 (完成)
const removeGoodsBrowse = async (params = {}) => {
  try {
    let { user, id } = params;
    // 删除数据库中已经过期的token记录
    try {
      await MYSQL.promise().query(
        `DELETE FROM ${userGoodsBrowseSqlName} 
      WHERE
      user = '${user}'
      and
      id = ${id}
      `
      );
    } catch (error) {
      console.log(error);
      throw { code: 500, msg: "删除失败,数据库操作失败" };
    }

    return {
      code: 0,
      msg: "删除成功",
    };
  } catch (error) {
    throw error;
  }
};
// 清空商品浏览记录 (完成)
const emptyGoodsBrowse = async (params = {}) => {
  try {
    let { user } = params;
    // 删除数据库中已经过期的token记录
    try {
      await MYSQL.promise().query(
        `DELETE FROM ${userGoodsBrowseSqlName} 
      WHERE
      user = '${user}'
      `
      );
    } catch (error) {
      console.log(error);
      throw { code: 500, msg: "清空失败,数据库操作失败" };
    }

    return {
      code: 0,
      msg: "清空成功",
    };
  } catch (error) {
    throw error;
  }
};

// 删除商品
const removeGoods = async (params = {}) => {};
// 编辑商品
const updateGoods = async (params = {}) => {};
// 新增商品
const addGoods = async (params = {}) => {};

// 店铺列表
const storeList = async (params = {}) => {
  try {
    let query = `SELECT * FROM ${shoppingStoreSqlName}`;
    let result = await MYSQL.promise().query(query);
    return {
      code: 0,
      msg: "获取成功",
      data: result[0],
    };
  } catch (error) {
    throw error;
  }
};
// 店铺信息
const storeInfo = async (params = {}) => {
  try {
    let { id } = params;
    let query = `SELECT * FROM ${shoppingStoreSqlName} WHERE id = ${id}`;
    let result = await MYSQL.promise().query(query);
    return {
      code: 0,
      msg: "获取成功",
      data: result[0],
    };
  } catch (error) {
    throw error;
  }
};
// 删除店铺
const removeStore = async (params = {}) => {};
// 编辑店铺
const updateStore = async (params = {}) => {};
// 申请退店
// 申请退店列表
// 审批退店
// 拒绝退店
// 查询退店是否符合条件

// 商城规格列表
const shoppingSpecsList = async (params = {}) => {};
// 新增规格
const addShoppingSpecs = async (params = {}) => {};
// 删除规格
const removeShoppingSpecs = async (params = {}) => {};
// 编辑规格
const updateShoppingSpecs = async (params = {}) => {};

// 【商城服务模块】================================================

// 商城服务列表
const shoppingServiceList = async (params = {}) => {
  try {
    let { page = 1, limit = 10 } = params;

    let query = `
    SELECT * FROM ${shoppingServiceSqlName}
    `;
    let result = await MYSQL.promise().query(query);
    let list = result[0];
    return {
      code: 0,
      msg: "获取成功",
      data: {
        page,
        limit,
        data: list,
      },
    };
  } catch (error) {
    throw error;
  }
};
// 新增服务
const addShoppingServiceList = async (params = {}) => {};
// 编辑服务
const updateShoppingServiceList = async (params = {}) => {};
// 删除服务
const removeShoppingServiceList = async (params = {}) => {};

// 获取商品列表
const getGoodsList = async (params = {}) => {
  try {
    let query = `
    SELECT 
    *,
     (
      SELECT store_name from ${shoppingStoreSqlName} 
      WHERE id = ${listSQLName}.store 
    ) as store_name
    FROM  ${listSQLName}
    `;
    let result = await MYSQL.promise().query(query);
    let list = goodsDataHandle(result[0]);
    return {
      code: 0,
      msg: "获取成功",
      data: {
        list,
      },
    };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "获取失败" };
  }
};
// 获取商品服务
const SERVICE = async (params = {}) => {
  let id = params.id;
  if (!id) {
    throw { code: 500, msg: "商品id不能为空" };
  }
  let query = `
    SELECT 

    ${shoppingServiceSqlName}.* 

    FROM ${goodsServiceSqlName}
    LEFT JOIN ${shoppingServiceSqlName} 
		ON ${goodsServiceSqlName}.service_id = ${shoppingServiceSqlName}.id
    
    WHERE ${goodsServiceSqlName}.goods_id = ${id}
  `;

  let result = await MYSQL.promise().query(query);
  return {
    code: 0,
    msg: "获取成功",
    list: result[0],
  };
};

// 【商品信息模块】================================================

// 获取商品信息
const GETGOODS = async (params = {}) => {
  try {
    let id = params.id;
    let query = `
      SELECT *,
     (
      SELECT store_name from ${shoppingStoreSqlName} 
      WHERE id = ${listSQLName}.store 
    ) as store_name
    FROM  ${listSQLName}
    `;
    if (id) {
      query += ` WHERE id = ${id}`;
    }
    let result = await MYSQL.promise().query(query);
    let list = goodsDataHandle(result[0]);
    return {
      code: 0,
      msg: "获取成功",
      list: list,
    };
  } catch (error) {
    console.log("格式化数据失败");
    console.log(error);
    throw {
      code: 500,
      msg: "格式化数据失败",
    };
  }
};

// 获取商品规格列表
const GETSPECS = async (params = {}) => {
  try {
    let id = params.id;
    if (!id) {
      throw { code: 500, msg: "商品id不能为空" };
    }
    let query = `
    SELECT 

    ${specsSqlName}.id,
    ${shoppingSpecsKeySqlName}.id as specsGroupId,
    ${shoppingSpecsKeySqlName}.name as name,
    ${specsSqlName}.specs_name,
    ${specsTagSqlName}.tag_id,
		${shoppingTagSqlName}.name as tag_name,
		${shoppingTagSqlName}.background as tag_background,
		${shoppingTagSqlName}.color as tag_color,
		${shoppingTagSqlName}.fontsize as tag_fontsize

    FROM ${specsSqlName} 

    LEFT JOIN ${shoppingSpecsKeySqlName} 
		ON ${specsSqlName}.specs_key_id = ${shoppingSpecsKeySqlName}.id
		
    LEFT JOIN ${specsTagSqlName}
    ON ${specsSqlName}.id = ${specsTagSqlName}.specs_id  
		
		LEFT JOIN ${shoppingTagSqlName}
    ON ${specsTagSqlName}.tag_id = ${shoppingTagSqlName}.id 

    WHERE goods_specs.goods_id = ${id}

  `;

    let result = await MYSQL.promise().query(query);
    let handleSpecsList = [];
    let list = result[0];
    list.forEach((item) => {
      let name = item.name;
      let value = item.specs_name;
      let id = item.id;

      // 规格组id
      let specsGroupId = item.specsGroupId;

      let pushData = {
        id,
        value,
      };

      if (handleSpecsList.some((i) => i.name == name)) {
        let index = handleSpecsList.findIndex((i) => i.name == name);
        let specsList = handleSpecsList[index].specslist;
        if (!specsList.some((k) => k.value == value && k.id == id)) {
          specsList.push(pushData);
        }
      } else {
        handleSpecsList.push({
          id: specsGroupId,
          name,
          specslist: [pushData],
        });
      }
    });
    return {
      code: 0,
      msg: "获取成功",
      list: handleSpecsList,
    };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "获取规格失败" };
  }
};
// 获取SPU列表
const GETSPU = async (params = {}) => {
  let id = params.id;
  if (!id) {
    throw { code: 500, msg: "商品id不能为空" };
  }
  let query = `SELECT * FROM ${goodsSpuSqlName} WHERE goods_id = ${id}`;
  let result = await MYSQL.promise().query(query);
  let list = result[0];
  let handleList = list.map((item) => {
    delete item.goods_id;
    delete item.id;
    return item;
  });
  return {
    code: 0,
    msg: "获取成功",
    list: handleList,
  };
};
// 获取SKU列表
const GETSKU = async (params = {}) => {
  let id = params.id;
  if (!id) {
    throw { code: 500, msg: "商品id不能为空" };
  }
  let query = `SELECT * FROM ${goodsSkuSqlName} WHERE goods_id = ${id}`;
  let result = await MYSQL.promise().query(query);
  let list = result[0];

  let handleList = list.map((item) => {
    item.stock = Number(item.stock);
    item.price = Number(item.price);
    return item;
  });

  return {
    code: 0,
    msg: "获取成功",
    list: handleList,
  };
};
// 获取商品信息
async function goodsinfo(params = {}) {
  try {
    let { id } = params;
    if (!id) {
      throw { code: 500, msg: "商品id不能为空" };
    }
    //   商品记录
    let goods_data = await GETGOODS({ id });
    //   商品SPU
    let spu_data = await GETSPU({ id });
    //   商品SKU
    let sku_data = await GETSKU({ id });
    // 商品规格
    let specs_data = await GETSPECS({ id });
    // 商品服务
    let service_data = await SERVICE({ id });

    return {
      code: 0,
      msg: "获取成功",
      data: {
        ...goods_data.list[0],
        spu: spu_data.list,
        sku: sku_data.list,
        specs: specs_data.list,
        service: service_data.list,
      },
    };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "获取失败" };
  }
}

// 【商城类目管理模块】================================================

// 获取商城类目列表
const ShoppingTypeList = async (params = {}) => {
  try {
    let query = `
      SELECT * FROM ${shoppingTypeSqlName} as f  WHERE type in (1,2,3) and state = 1 
    `;
    try {
      let result = await MYSQL.promise().query(query);
      return {
        code: 0,
        msg: "获取成功",
        data: formatTypeList(result[0]),
      };
    } catch (error) {
      console.log(error);
      throw {
        code: 500,
        msg: "获取商城类目失败",
      };
    }
  } catch (error) {
    throw error;
  }
};
// 删除商城类目
const removeShoppingType = async (params = {}) => {};
// 更新商城类目信息
const updateShoppingType = async (params = {}) => {};
// 新增商城类目
const addShoppingType = async (params = {}) => {};

module.exports = {
  goodsinfo, // 获取商品信息
  getGoodsList, // 获取商品列表

  goodsCartList, // 获取购物车列表
  removeGoodsCart, // 删除购物车商品
  addGoodsCart, // 新增购物车商品

  storeList, // 获取店铺列表
  storeInfo, // 获取店铺信息
  removeStore, // 删除店铺
  updateStore, // 更新店铺

  ShoppingTypeList, // 获取商城类目列表
  shoppingSpecsList,
  addShoppingSpecs,
  removeShoppingSpecs,
  updateShoppingSpecs,
  addShoppingServiceList,
  shoppingServiceList,
  updateShoppingServiceList,
  removeShoppingServiceList,
  removeShoppingType,
  updateShoppingType,

  emptyGoodsBrowse, // 清空商品浏览记录
  removeGoodsBrowse, // 删除商品浏览记录
  addGoodsBrowse, // 新增商品浏览记录

  collectList, // 我的收藏列表
  addCollect, // 添加收藏
  cancelCollect, // 取消收藏
};
